package com.Socket.tongxinlx;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class SocketTCP03 {
    public static void main(String[] args) throws IOException {
        //服务器端口999
        Socket socket = new Socket(InetAddress.getLocalHost(),9999);
        System.out.println(socket.getClass());
        //链接上后，通过getOutputStream得到和socket对象关联的输出流对象
        OutputStream outputStream = socket.getOutputStream();

        //通过输出流，写入数据到数据通道，使用字符流
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("hello,server 字符流");
        bufferedWriter.newLine();//插入一个换行符，表示写入的内容结束，注意，要求对方使用readLine（）！！！
        bufferedWriter.flush();//如果使用字符流，需要手动刷新，否则数据不会写入数据通道

        //获取和socket关联的输入流，读取数据（字节），并显示
        InputStream inputStream = socket.getInputStream();
//        byte[] bytes = new byte[1024];
//        int readLen = 0;
//        while ((readLen = inputStream.read(bytes)) != -1){
//            System.out.println(new String(bytes,0,readLen));
//        }
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = bufferedReader.readLine();
        System.out.println(s);
        //关闭流
        bufferedReader.close();
//        inputStream.close();
        bufferedWriter.close();
//        outputStream.close();
        socket.close();
        System.out.println("客户端结束。。");

    }
}
